package com.benew.ntt.player.utils;

import com.google.android.exoplayer2.util.Log;

import java.math.BigDecimal;

public class VolumeUtils {

    private static final int VOLUME_BALANCE_MIN = -255; //音量均衡默认值

    /**
     * 音量均衡
     *
     * @param volume
     * @return
     */
    public static float calculateBalanceVolume(int volume) {
        if (isInvalidVolume(volume)) return 1.0f;
        int gain = calculateGain(4 * volume);
        Log.d("VolumeUtils", "volume:" + volume + ", calculateBalanceVolume:" + gain + "db");
        float vol = (float) convertToAmplitude(gain);
        return vol;
    }

    private static double convertToAmplitude(int db) {
        double d = Math.pow(10, (double) db / 20);
        BigDecimal b = new BigDecimal(d);
        d = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if(d == 0)
            d = 0.01;
        return d;
    }

    /**
     * 无效音量均衡
     * @return
     */
    private static boolean isInvalidVolume(int volume) {
        return volume <= VOLUME_BALANCE_MIN || volume == 0;
    }


    private static int calculateGain(int musicVolume) {
        if (musicVolume < 2)
            return -36;
        else if (musicVolume > 189214)
            return 44;

        int musicVolumeRange[] = {2, 2, 3, 3, 4, 4, 5, 6,
                7, 8, 9, 10, 12, 14, 16, 18,
                20, 24, 28, 32, 35, 44, 49, 57,
                65, 75, 86, 100, 115, 132, 153, 176,
                203, 234, 270, 312, 360, 415, 478, 552,
                636, 733, 846, 975, 1124, 1296, 1495, 1724,
                1987, 2292, 2642, 3047, 3513, 4050, 4670, 5385,
                6209, 7159, 8254, 9517, 10974, 12653, 14589, 16821,
                19395, 22362, 25783, 29728, 34276, 39521, 45568, 52540,
                60578, 69847, 80534, 92855, 107062, 123443, 142329, 164106,
                189214};  // min 100*1.153^-27  max 100*1.153^53
        int low = 0;
        int high = 80;
        int mid = 0;
        while (low <= high) {
            mid = (low + high) / 2;
            if (musicVolumeRange[mid] == musicVolume) {
                return mid - 36;  // found
            } else {
                if (musicVolumeRange[mid] < musicVolume) {
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }
        }
        return mid - 36;  // not find
    }
}
